import akshare as ak
import mplfinance as mpf
import pandas as pd
import datetime

if __name__ == '__main__':
    print(ak.__version__)

    stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol="600111", period="daily", start_date="20250622", end_date='20250922',
                                            adjust="")
    print(stock_zh_a_hist_df)

    # 将日期设为索引，并转换为日期格式（这步很重要！）
    stock_zh_a_hist_df['日期'] = pd.to_datetime(stock_zh_a_hist_df['日期'])
    stock_zh_a_hist_df.set_index('日期', inplace=True)

    # 确保列名符合mplfinance的要求
    df = stock_zh_a_hist_df.rename(columns={
        '开盘': 'Open',
        '最高': 'High',
        '最低': 'Low',
        '收盘': 'Close',
        '成交量': 'Volume'
    })

    print(f"最低位-${df['Low'].min()}")
    print(f"最高位-${df['High'].max()}")

    # 筛选近N个月的数据
    n_months_ago = datetime.datetime.now() - datetime.timedelta(days=90)
    recent_data = df[df.index >= n_months_ago]

    # 找出下跌的K线
    down_days = recent_data[recent_data['Close'] < recent_data['Open']]

    #找出上涨的K线
    up_days = recent_data[recent_data['Close'] >= recent_data['Open']]

    if down_days.empty or up_days.empty:
        print(f"近2个月没有下跌或上涨的K线")
    else:
        # 找到下跌K线中的最低收盘价
        lowest_close = down_days['Close'].min()
        # 获取最低收盘价日期
        lowest_close_date = down_days[down_days['Close'] == lowest_close].index[0]
        print(f"最低收盘价${lowest_close}-----最低收盘价日期${lowest_close_date.strftime('%Y-%m-%d')}")
        # 获取最低收盘价的价格
        lowest_date = down_days[down_days['Close'] == lowest_close].index[0]


       # 找到最低收盘价K线日期往后的所有上涨的K线
        print(f"日期--${up_days.index.strftime('%Y-%m-%d')}")
        subsequent_data = up_days[up_days.index >= lowest_close_date]

        #找到上涨K线中成交量最大K线
        top_volume_data = subsequent_data.nlargest(1, 'Volume')
        #获取成交量最高的K线的收盘价
        max_volume_price = top_volume_data['Close'].iloc[0]
        # 获取成交量最大收盘价日期
        max_volume_date = top_volume_data.index[0]
        print(f"成交量最高K线日期${max_volume_date.strftime('%Y-%m-%d')}")

        # 找到上涨K线中的最高收盘价
        highest_close = subsequent_data['Close'].max()
        highest_close_date = subsequent_data[subsequent_data['Close'] == highest_close].index[0]
        print(f"最高收盘价${highest_close}-----最高收盘价日期${highest_close_date.strftime('%Y-%m-%d')}")

        if lowest_close_date < max_volume_date:
            start_date = lowest_close_date
            end_date = max_volume_date
        else:
            start_date = max_volume_date
            end_date = lowest_close_date
        print(f"开始日期：${start_date.strftime('%Y-%m-%d')}--截止日期:${end_date.strftime('%Y-%m-%d')}")
        # 筛选出成交量最大的K线日期和最低价格K线之间的所有K线
        filtered_up_days = up_days[(up_days.index > start_date) & (up_days.index < end_date)]
        # 找出成交量前2的K线
        two_top_volume_data = filtered_up_days.nlargest(2, 'Volume')
        # 获取第一根的价格
        first_row = two_top_volume_data.iloc[0]['Close']
        first_date = two_top_volume_data.index[0]
        print(f"成交量第二高K线价格${first_row}--日期:${first_date.strftime('%Y-%m-%d')}")
        # 获取第二根的价格
        second_row = two_top_volume_data.iloc[1]['Close']
        second_date = two_top_volume_data.index[1]
        print(f"成交量第三高K线价格${second_row}--日期:${second_date.strftime('%Y-%m-%d')}")

        # 创建支撑线
        support_line = [lowest_close] * len(df)

        # 创建压力线
        yali_line =  [highest_close] * len(df)

        # 创建成交量最高的线
        max_volume_line = [max_volume_price] * len(df)

        #  创建成交量第二高的线
        second_max_volume_line = [first_row] * len(df)
        third_max_volume_line = [second_row] * len(df)

        # 添加移动平均线
        ma20 = df['Close'].rolling(20).mean()

        # 5. 使用make_addplot画线
        apd = [
            mpf.make_addplot(support_line,
                             color='green',
                             linestyle='--',
                             label=f'近2月下跌最低价: {lowest_close:.2f}'),
            mpf.make_addplot(max_volume_line,
                             color='red',
                             linestyle='--',
                             label=f'成交量最高的价格: {float(max_volume_price):.2f}'),
            mpf.make_addplot(second_max_volume_line,
                             color='blue',
                             linestyle='--',
                             label=f'成交量第二高的价格: {float(max_volume_price):.2f}'),
            mpf.make_addplot(third_max_volume_line,
                             color='pink',
                             linestyle='--',
                             label=f'成交量第三高的价格: {float(max_volume_price):.2f}'),
        ]


        # 自定义颜色配置
        custom_style = mpf.make_marketcolors(
            up='red',  # 上涨颜色
            down='green',  # 下跌颜色
            edge='inherit',  # K线边框颜色
            wick={'up': 'red', 'down': 'green'},  # 上下影线颜色
            volume='blue',  # 成交量颜色
            ohlc='i',  # 使用独立的OHLC颜色
            alpha=0.9  # 透明度
        )

        # 创建样式
        style = mpf.make_mpf_style(
            marketcolors=custom_style,
            gridstyle='--',  # 网格线样式
            gridcolor='lightgray',
            facecolor='white',  # 背景颜色
            edgecolor='black',
            figcolor='white',
            y_on_right=False  # Y轴在左边
        )

        # 画K线图
        mpf.plot(df,
                 type='candle',  # 类型：candle(K线), line(线图), ohlc(美国线)
                 style=style,  # 样式：charles, classic, mike, etc.
                 title='晋控电力 (000767) K线图',
                 addplot=apd,
                 volume=True,  # 显示成交量
                 mav=(5, 10, 20),  # 移动平均线：5日、10日、20日
                 figratio=(12, 6),  # 图形比例
                 figscale=1.2)  # 图形缩放
